package com.zhl.controller;

import com.alibaba.druid.util.StringUtils;
import com.zhl.entity.Article;
import com.zhl.entity.User;
import com.zhl.entity.ZhlResult;
import com.zhl.entity.pojo.ArticleVo;
import com.zhl.service_.ArticleService;
import com.zhl.service_.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2018/11/2.
 * 日记本(管理后台需要权限控制)
 */
@Controller
@Api(tags = "日记本相关接口")
public class ArticleController {

    Logger logger = LoggerFactory.getLogger("ArticleController");

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserService userService;

    /**
     * 查询所有日记
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @ResponseBody
    @ApiOperation(value = "查询所有日记", httpMethod = "GET")
    @GetMapping("/api/article")
    public ZhlResult articleList(@ApiParam(value = "页码") @RequestParam int pageNumber, @ApiParam(value = "每页行数") @RequestParam int pageSize, @ApiParam(value = "文章类型") @RequestParam String articleType, @ApiParam(value = "标题") @RequestParam String title) {
        logger.info("查询日记,pageNumber={},pageSize={},articleType={},title={}",pageNumber,pageSize,articleType,title);

        List<Article> articles = articleService.articleList(pageNumber,pageSize, articleType, title);
        int count = articleService.getCount();
        ZhlResult zhlResult = ZhlResult.ok(articles);
        zhlResult.setTotalCount(count);
        return zhlResult;

    }

    /**
     * 添加日记
     * @param article
     * @return
     */
    @RequestMapping(value = "/api/addarticle", method = RequestMethod.POST)
    @ApiOperation(value = "添加日记", httpMethod = "POST")
    @ResponseBody
    public ZhlResult addArticle(HttpServletRequest request, Article article) {

        if(StringUtils.isEmpty(article.getTitle())) {
            return ZhlResult.fail("标题不能为空");
        }
        if(StringUtils.isEmpty(article.getContent())) {
            return ZhlResult.fail("内容不能为空");
        }

        User user = (User)request.getSession().getAttribute("user");

        Date date = new Date();
        String datestr = this.format.format(date);
        article.setCreateTime(datestr);
        article.setUpdateTime(datestr);

        article.setUserid(user.getId());

        logger.info("添加日记:" + article.toString());
        articleService.addArticle(article);
        ZhlResult zhlResult = ZhlResult.ok();
        return zhlResult;
    }

    /**
     * 根据id查询日记
     * @return
     */
    @RequestMapping("/admin/modify/{id}")
    @ApiOperation(value = "添加日记", httpMethod = "GET")
    public String modifyArticle(@ApiParam(value = "日记id") @PathVariable("id") int id, Model model) {
        logger.info("查询日记,article_id:"+id);

        Article article = articleService.queryArticleById(id);
        model.addAttribute("article",article);

        return "admin/modify.html";

    }

    /**
     * 修改日记
     * @return
     */
    @RequestMapping("/api/updatearticle")
    @ResponseBody
    @ApiOperation(value = "添加日记", httpMethod = "POST")
    public ZhlResult updateArticle(Article article) {

        int id = article.getId();
        logger.info("修改日记,article_id:"+id);

        Article oldarticle = articleService.queryArticleById(id);
        if(oldarticle== null) {
            return ZhlResult.build(400,"该id没有对用的文章");
        }

        Date date = new Date();
        String datestr = this.format.format(date);
        oldarticle.setUpdateTime(datestr);
        oldarticle.setTitle(article.getTitle());
        oldarticle.setArticleType(article.getArticleType());
        oldarticle.setCover(article.getCover());
        oldarticle.setIsOriginal(article.getIsOriginal());
        oldarticle.setSynopsis(article.getSynopsis());
        oldarticle.setContent(article.getContent());

        articleService.updateArticle(oldarticle);

        return ZhlResult.ok();

    }

    /**
     * 删除日记
     *
     */
    @RequestMapping("/api/deletearticle/{id}")
    @ResponseBody
    public ZhlResult deleteArticle(@ApiParam(value = "日记id")@PathVariable("id") int id, Model model) {
        logger.info("查询日记,article_id:"+id);

        Article oldarticle = articleService.queryArticleById(id);
        if(oldarticle== null) {
            return ZhlResult.build(400,"该id没有对用的文章");
        }

        articleService.deleteArticle(id);
        return ZhlResult.ok();

    }




    /**
     * 查看日记详情
     * @return
     */
    @RequestMapping("/context/{id}")
    public String queryArticleById(@ApiParam(value = "日记id")@PathVariable("id") int id, Model model) {
        logger.info("查看日记article_id:"+id);

        Article article = articleService.queryArticleById(id);

        //点击量加1
        int clickRate = article.getClickRate() + 1;
        article.setClickRate(clickRate);
        articleService.updateArticle(article);

        int userid = article.getUserid();

        User user = userService.queryUserByid(userid);

        ArticleVo articleVo = new ArticleVo();
        BeanUtils.copyProperties(article,articleVo);
        articleVo.setIcon(user.getIcon());
        articleVo.setNickName(user.getNickname());

        model.addAttribute("article",articleVo);

        return "context.html";

    }


}
